//
//  AlbumViewController.m
//  Everest
//
//  Created by 李其昌 on 14/12/17.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "AlbumViewController.h"
#import "ClassifyDetail.h"
#import "Album.h"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "AlbumTableViewCell.h"
#import "AlbumTracks.h"
#import "DownloadCell.h"
#import "PlayViewController.h"
#import "HotPresent.h"
#import "DataBaseHandler.h"
#import "UIColor+AddColor.h"

#define DETAIL_HIGHT 210  // 显示图片的高度
#define FINAL_HIGHT 0    // 上拉滑动最终留下的显示图片高度
#define IMAGEVIEW_ORIGIN_Y -60  // 图片的实际起点纵坐标
#define IMAGEVIEW_ORIGIN_HEITH 500  // 图片的实际高度

#define REUSING @"reuse"
#define DOWREUSE @"dowreuse"
#define ALBUM @"album"
#define TRACKS @"tracks"
#define LIST @"list"

@interface AlbumViewController ()<UITableViewDataSource, UITableViewDelegate>
// 视图
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) UIImageView *minImageView;
@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) UITextView *textView;
@property (nonatomic, retain) UIView *bigTextView;
// 要使用的类和数组
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) Album *album;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UISegmentedControl *segment;
@property (nonatomic, retain) NSMutableArray *tracksArr;
@property (nonatomic, retain) UIAlertView *alertView;
@property (nonatomic, retain) UIView *tabBarView;
// 用来判断segment的坐标和重用池
@property (nonatomic, assign) int count;

@end

@implementation AlbumViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        self.count = 1;
//        [self handleData];
        
        NSNotificationCenter *ficationCollect = [NSNotificationCenter defaultCenter];
        [ficationCollect addObserver:self selector:@selector(ficationCollectAction:) name:@"album" object:nil];
        
    }
    return self;
}
// 在此方法中调用处理数据的方法
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [self handleData];
    
}


- (void)dealloc
{
    [_tabBarView release];
    [_collect release];
    [_tracksArr release];
    [_nameLabel release];
    [_minImageView release];
    [_imageView release];
    [_bigTextView release];
    [_textView release];
    [_segment release];
    [_tableView release];
    [_album release];
    [_arr release];
    [super dealloc];
}
// 处理数据的方法
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/30?device=iPhone", [self.classifyDetail.pageId description]];
    
//    NSLog(@"%@", str);
    
    self.tracksArr = [NSMutableArray array];
    // 数据请求与解析
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *albumDic = [resultDic objectForKey:ALBUM];
        NSDictionary *tracksDic = [resultDic objectForKey:TRACKS];
        NSArray *array = [tracksDic objectForKey:LIST];
        
        
        self.album = [[Album alloc] initWithDictionary:albumDic];
        
        for (NSDictionary *dic in array) {
            
            AlbumTracks *tracks = [[AlbumTracks alloc] initWithDictionary:dic];
            
            [self.tracksArr addObject:tracks];
            
            [tracks release];
        }
        
        [_album release];
        
        // 背景图片的请求
        NSURL *url = [NSURL URLWithString:self.album.coverOrigin];
        [self.imageView setImageWithURL:url];
        
        // 小图片的请求
        NSURL *urlMin = [NSURL URLWithString:self.album.coverLarge];
        [self.minImageView setImageWithURL:urlMin];
        
        // 播主名字的赋值
        self.nameLabel.text = self.album.nickname;
        
        NSString *str = [NSString stringWithFormat:@"专辑名称：无\n\n创建人：%@\n\n分享：0\n\n标签：%@\n\n简介：\n\n%@", self.album.nickname, self.album.tags, self.album.intro];
        self.textView.text = str;
        self.textView.font = [UIFont systemFontOfSize:14];
        self.textView.textColor = [UIColor grayColor];
        // 刷新数据
        [self.tableView reloadData];
        if (self.tracksArr.count < 3) {
            self.tableView.scrollEnabled = NO;
        } else {
            self.tableView.scrollEnabled = YES;
        }
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.classifyDetail.title;
//    self.navigationController.navigationBar.alpha = 0.3;
    self.navigationController.navigationBar.translucent = NO;
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(barAction:)];
//    self.navigationItem.hidesBackButton = YES;



//    self.tabBarController.tabBar.hidden = YES;

//    self.navigationItem.title = self.classifyDetail.title;
//    self.navigationItem.title = @"123456";
//    // 自定义tabbar
//    self.tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49)];
//    [self.view addSubview:self.tabBarView];
//    self.tabBarView.backgroundColor = [UIColor tabBarColor];
//    // 返回键
//    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [self.view addSubview:backButton];
//    backButton.frame = CGRectMake(10, 10, 30, 29);
//    [backButton setImage:[UIImage imageNamed:@"iconfont-gerenfanhui.png"] forState:UIControlStateNormal];
//    [backButton setTintColor:[UIColor sectionColor]];
//    [backButton addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
//    // 自定义tabbar
//    self.tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49)];
//    [self.view addSubview:self.tabBarView];
//    self.tabBarView.backgroundColor = [UIColor redColor];
//    // 返回键
//    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    [self.view addSubview:backButton];
//    backButton.frame = CGRectMake(10, 10, 30, 29);
//    [backButton setImage:[UIImage imageNamed:@"iconfont-gerenfanhui.png"] forState:UIControlStateNormal];
//    [backButton setTintColor:[UIColor sectionColor]];
//    [backButton addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
//    self.tabBarController.tabBar.hidden = YES;
    
    
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, IMAGEVIEW_ORIGIN_Y, self.view.frame.size.width, IMAGEVIEW_ORIGIN_HEITH)];
    
//    NSURL *url = [NSURL URLWithString:self.album.coverOrigin];
//    [self.imageView setImageWithURL:url];
    [self.view addSubview:self.imageView];
    
    [_imageView release];
    
    self.bigTextView = [[[UIView alloc] initWithFrame:CGRectMake(0, 160, self.view.bounds.size.width, self.view.bounds.size.height)] autorelease];
    self.bigTextView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bigTextView];
    // NSLog(@"%lf", self.view.bounds.size.height);
    self.bigTextView.hidden = YES;
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 300)];
    self.textView.font = [UIFont systemFontOfSize:17];
    self.textView.backgroundColor = [UIColor whiteColor];
    [self.bigTextView addSubview:self.textView];
    self.textView .autoresizingMask = UIViewAutoresizingFlexibleHeight;
    self.textView.scrollEnabled = YES;
    self.textView.editable = NO;
    [_textView release];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 260, self.view.bounds.size.width, self.view.bounds.size.height)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    [whiteView release];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height - FINAL_HIGHT) style:UITableViewStylePlain];
    self.tableView.tableFooterView = [[[UIView alloc] init] autorelease];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 104, 0);
    [self.view addSubview:self.tableView];
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 130)];
    view.opaque = YES;
    self.tableView.tableHeaderView = view;
    [_tableView release];
    
    
    UIView *backView = [[UIView alloc] initWithFrame:self.imageView.bounds];
//    NSLog(@"%.f", self.imageView.bounds.size.width);
    backView.backgroundColor = [UIColor whiteColor];
    backView.alpha = 0.9;
    [self.imageView addSubview:backView];
    [backView release];
    
//    // cell 的注册
//    [self.tableView registerClass:[AlbumTableViewCell class] forCellReuseIdentifier:REUSING];
//    [self.tableView registerClass:[DownloadCell class] forCellReuseIdentifier:DOWREUSE];
    
    self.minImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 10.5, self.view.frame.size.height / 50, self.view.frame.size.width / 3.5, self.view.frame.size.height / 6)];

    [view addSubview:self.minImageView];
    [_minImageView release];
    
    // 创建人的名字
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 10.5 + self.view.frame.size.width / 3.5 + 20, self.view.frame.size.height / 50, self.minImageView.frame.size.width, self.minImageView.frame.size.height / 2)];
    
    [view addSubview:self.nameLabel];
    [_nameLabel release];
    
    UILabel *CJLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 10.5 + self.view.frame.size.width / 3.5 + 20 + self.minImageView.frame.size.width, self.view.frame.size.height / 50, self.view.frame.size.width / 8, self.minImageView.frame.size.height / 2)];
    CJLabel.text = @"创建";
    [view addSubview:CJLabel];
    [CJLabel release];
    
    // 访问播主按钮
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    button.frame = CGRectMake(self.view.frame.size.width / 2.7, self.view.frame.size.height / 50 + self.minImageView.frame.size.height / 2,self.minImageView.frame.size.width, self.minImageView.frame.size.height / 2);
//    [button setTitle:@"访问播主" forState:UIControlStateNormal];
    
//    [view addSubview:button];
    
    // 收藏按钮
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    collectButton.frame = CGRectMake(self.view.frame.size.width / 10.5 + self.view.frame.size.width / 3.5 + 20 + self.minImageView.frame.size.width, self.view.frame.size.height / 50 + self.minImageView.frame.size.height / 2, self.view.frame.size.width / 8, self.minImageView.frame.size.height / 2);
    [collectButton addTarget:self action:@selector(collectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    [view addSubview:collectButton];
    

}
// 动画效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat content = scrollView.contentOffset.y;
    CGRect newFrame = self.imageView.frame;
    
    if (content < 0) {
        
        newFrame.origin.y = IMAGEVIEW_ORIGIN_Y - content / 5;
        self.imageView.frame = newFrame;
        
    } else if (content > 0 && content < DETAIL_HIGHT)
    
        newFrame.origin.y = IMAGEVIEW_ORIGIN_Y - content;
        self.imageView.frame = newFrame;
    
}
//- (void)backButtonClicked:(UIButton *)button
//{
//    NSLog(@"返回上一页");
//    [self.navigationController popViewControllerAnimated:YES];
//}
// section 的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
// section 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
// section 上的segmentedControl控件
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *array = [NSArray arrayWithObjects:@"简介", @"排序", @"相关专辑", nil];

    self.segment = [[[UISegmentedControl alloc] initWithItems:array] autorelease];
    self.segment.frame = CGRectMake(0, 0, 375, 30);
    self.segment.selectedSegmentIndex = self.count;
    self.segment.backgroundColor = [UIColor whiteColor];
    self.segment.tintColor = [UIColor kuGouColor];
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    
    return self.segment;
}
// segment 的方法
- (void)segmentAction:(UISegmentedControl *)seg
{
    
    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            self.tableView.scrollEnabled = NO;
            self.bigTextView.hidden = NO;
            [self.view bringSubviewToFront:self.bigTextView];
//            [self.view bringSubviewToFront:self.tabBarView];
        }
            break;
            
        case 1:
        {
            self.tableView.scrollEnabled = YES;
            self.bigTextView.hidden = YES;
            [self.view bringSubviewToFront:self.tableView];
//            [self.view bringSubviewToFront:self.tabBarView];
            [self.tracksArr removeAllObjects];
            [self.tableView reloadData];
            [self handleData];
            self.count = 1;
            
        }
            break;
            
        case 2:
        {
            
            [self lendData];
            [self.tableView reloadData];
            self.tableView.scrollEnabled = YES;
            self.bigTextView.hidden = YES;
            [self.view bringSubviewToFront:self.tableView];
//            [self.view bringSubviewToFront:self.tabBarView];
            self.count = 2;
            
        }
            break;
            
        default:
            break;
    }
    
    
    
}
// cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.count == 1) {
        
    AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    
//    CGRect rect = [tracks.title boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width / 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    
//    NSString *title = [[self.hotPresentArr objectAtIndex:indexPath.section] title];
//    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [tracks.title boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width / 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    CGFloat height = rect.size.height > (kCellWidth / 6) ? rect.size.height : (kCellWidth / 6);
    return height + 55;
    
//    return rect.size.height + self.view.bounds.size.height / 667 * 35 + 50;
    } else if (self.count == 2) {
            AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
//        NSString *title = [[self.albumArr objectAtIndex:indexPath.row] title];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        
        CGRect rect = [tracks.title boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width / 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + self.view.bounds.size.height / 667 * 40 + 15;
    }
    return 0;
}

// cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 根据count的值不同跳到不同的页面
    if (self.count == 1) {
        
        PlayViewController *playVC = [PlayViewController defaultPlayVC];
        if (playVC.hotPlayArr.count != 0) {
            [playVC.hotPlayArr removeAllObjects];
        }
        if (playVC.focusFetailArr.count != 0) {
            [playVC.focusFetailArr removeAllObjects];
        }
        AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
        if (tableView == self.tableView) {
            playVC.index = indexPath.row;
            
        }
        playVC.albumArr = [NSMutableArray arrayWithArray:self.tracksArr];
        playVC.album = tracks;
        [self presentViewController:playVC animated:YES completion:^{
            
            
        }];
        
        
        
    } else if (self.count == 2) {
        
        AlbumViewController *albumVC = [[AlbumViewController alloc] init];
        
        AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
        
        ClassifyDetail *classify = [[ClassifyDetail alloc] init];
        
        classify.pageId = tracks.albumId;
        
        albumVC.classifyDetail = classify;
        
        [self.navigationController pushViewController:albumVC animated:YES];
        
        [albumVC release];
        [classify release];
        
//        [self removeFromParentViewController];
    }
    
}

// tableView 必须实现两个的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tracksArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"segment = %ld", self.segment.selectedSegmentIndex);
    
    
    if (self.count == 2) {
        
        DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:DOWREUSE];
        
        if (cell == nil) {
            
            cell = [[DownloadCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:DOWREUSE];
            
        }
        
        AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
        
        cell.tracks = tracks;
        
        return cell;
        
    } else {
        
        AlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:REUSING];
        
        if (cell == nil) {
            
            cell = [[AlbumTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:REUSING];
            
        }
        
        AlbumTracks *tracks = [self.tracksArr objectAtIndex:indexPath.row];
        
        cell.tracks = tracks;
        
        return cell;

        
    }
    
}
// 右上角返回按钮方法
- (void)barAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
// 当segment下标为2时调用的方法
- (void)lendData
{
    [self.tracksArr removeAllObjects];
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/%@/1/30?device=iPhone", self.album.uid];
    
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = [resultDic objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            
            AlbumTracks *tracks = [[AlbumTracks alloc] initWithDictionary:dic];
            
            [self.tracksArr addObject:tracks];
            
            [tracks release];
            
        }
        // 刷新数据
        [self.tableView reloadData];
    }];
     self.segment.selectedSegmentIndex = 2;

}

- (void)ficationCollectAction:(NSNotification *)noti
{
    self.collect = @"YES";
}

// 收藏按钮
- (void)collectButtonClicked:(UIButton *)button
{
    if ([self.collect isEqualToString:@"YES"]) {
        
        DataBaseHandler *handler = [DataBaseHandler shareInstance];
        
        [handler insertString:self.album];
        
        //    NSString *homePath = NSHomeDirectory();
        //    NSLog(@"%@", homePath);
        
    } else {
    
        self.alertView = [[UIAlertView alloc] initWithTitle:@"请登录" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [self.alertView show];
        [_alertView release];
        
        [NSTimer scheduledTimerWithTimeInterval:0.8f
                                         target:self
                                       selector:@selector(dismissAlert:)
                                       userInfo:nil
                                        repeats:NO];
   
    }
}
- (void)dismissAlert:(NSTimer *)timer{
    
    
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
